<template>
    <div class="content">
       
        <p>{{ $route.query.id }} {{ route.query.id_id }}</p>
        <div class="banner">
            <i class="iconfont icon-xiangzuojiantou icons" @click="$router.back()"></i>
            <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
                <van-swipe-item v-for="items, index in banner" :key="index">
                    <img :src="items" />
                </van-swipe-item>
            </van-swipe>
        </div>
        <div class="main">
            <div class="header_title">
                <van-button type="primary" size="small">必玩榜</van-button>
                <van-button type="primary" size="small">韩国夏威夷</van-button>
                <van-button type="primary" size="small">海岛风光</van-button>
            </div>
            <div v-for="item in detialisten" :key="item.id" class="header-h1">
                <h2>{{ item.spot_name }}</h2>
            </div>
            <div class="pj" v-for="item in detialisten" :key="item.id">
                <span>评分：{{ item.rating }}</span> <span>点赞数量：{{ likesnew }}</span>
            </div>
            <div class="tab-listen" v-for="item in detialisten" :key="item.id">
                <van-tabs v-model:active="activeName" @change="btnglClick">
                    <van-tab title="景点介绍" name="a">
                        <h2>景点介绍</h2>
                        <p>{{ item.description }}</p>
                        <h2>交通工具</h2>
                        <div class="icon_bus">
                            <i class="iconfont icon-qiche"></i>
                            <i class="iconfont icon-gongjiao"></i>
                            <i class="iconfont icon-motuoche"></i>
                            <i class="iconfont icon-feiji"></i>
                            <i class="iconfont icon-fanchuan"></i>
                        </div>
                        <!-- 接入地图 -->
                        <div class="maps">
                            <h2>地理位置</h2>
                            <div id="address" class="address">kkkk</div> <!-- 显示地址 -->
                            <div id="container"></div>
                        </div>
                        <div class="contents_main">
                            <div class="title">
                                <h1>最佳游览时间</h1>
                                <p>{{ item.best_visit_time }}</p>
                                <p>4-6月是济州岛的春季，这时的济州岛气候宜人，樱花和油菜花纷纷绽放，景致迷人，连当地人都赞不绝口。</p>
                            </div>
                            <div class="title">
                                <h1>建议游玩天数</h1>
                                <p>{{ item.suggested_days_nums }}</p>
                                <p>{{ item.guide }}</p>
                            </div>
                            <div class="title">
                                <h1>消费水平</h1>
                                <p>{{ item.expense_level }}</p>
                                <p>{{ item.expense_level_title }}</p>
                            </div>
                        </div>
                    </van-tab>
                    <van-tab title="游玩攻略" name="b">
                        <ul>
                            <li class="gongl" v-for="itemsgl in playgl" :key="itemsgl.id">
                                <div class="left">
                                    <van-image :src="itemsgl.image_url" />
                                </div>
                                <div class="right">
                                    <h3 >{{ itemsgl.title }}</h3>
                                    <p>{{ itemsgl.description }}</p>
                                    <div class="icon-gz">
                                        <van-image
                                            src="https://cdn7.axureshop.com/demo2024/1212098/images/%E6%89%BE%E6%94%BB%E7%95%A5/u1299.png"></van-image>
                                        <span>西瓜</span>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </van-tab>
                    <van-tab title="热门游记" name="c">
                        <van-grid :column-num="2">
                            <van-grid-item v-for="item in recommendations" :key="item.id">
                                <van-image class="van-img" :src="item.image_url" />
                                <span style="margin-top: 0.05rem;">{{ item.title }}</span>
                                <div class="bottom_news">
                                    <div class="left">
                                        <van-image
                                            src="https://cdn7.axureshop.com/demo2024/1212098/images/%E9%A6%96%E9%A1%B5/u262.png"></van-image>
                                        <span>西瓜</span>
                                    </div>
                                    <div class="right">
                                        <van-image :src="item.liked ? 'https://cdn7.axureshop.com/demo2024/1212098/images/%E9%A6%96%E9%A1%B5/u261.png' : 'https://cdn7.axureshop.com/demo2024/1212098/images/%E9%A6%96%E9%A1%B5/u258.png' " @click="item.id !== undefined ? imgClick(item.id) : null" class="icons"></van-image>
                                        <span>{{ item.likes }}</span>
                                    </div>
                                </div>

                            </van-grid-item>

                        </van-grid>
                    </van-tab>
                </van-tabs>
            </div>

        </div>
        <div class="footer">
            <van-button class type="primary" @click="lvjhClick">加入旅行清单</van-button>
        </div>


    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted,computed, type Ref } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { spotDetailsFn, travelGuidesFn,travelPlansFn } from '@/API/changgeCity/changeCity';
import { recommendationsLikesFn } from '@/API/home';
import { fetchRecommendationsByCategory } from '@/API/home';
import { useRouter, useRoute } from 'vue-router';
const detialisten = ref() //所以详情数据
interface Recommendation {
    id?: number;
    title?: string;
    image_url?: string;
    likes?: number;
    name?: string;
    liked?: boolean; //是否喜欢
}

const icon = ref('https://cdn7.axureshop.com/demo2024/1212098/images/%E9%A6%96%E9%A1%B5/u258.png')
// https://cdn7.axureshop.com/demo2024/1212098/images/%E9%A6%96%E9%A1%B5/u261.png


const recommendations: Ref<Recommendation[]> = ref([]);  //热门游记数据
const router = useRouter()
const route = useRoute()
const banner = ref() //轮播图数据
const playgl = ref() //游玩攻略数据
const images = [
    'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg',
    'https://fastly.jsdelivr.net/npm/@vant/assets/apple-2.jpeg',
];
const activeName = ref('a');
let map: any = null;
onMounted(() => {
    (window as any)._AMapSecurityConfig = {
        securityJsCode: "e02bd180e452e60683608cd019858126",
    };
    AMapLoader.load({
        key: "9e57d49485ad6a5f2658791890581c4b", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Scale", "AMap.Geolocation", "AMap.Geocoder"], // 需要使用的插件列表
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                viewMode: "3D",
                zoom: 11,
                center: [116.397428, 39.90923], // 默认中心点
            });

            // 添加定位控件
            const geolocation = new AMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                timeout: 10000,           // 超过10秒后停止定位，默认：无穷大
                maxWaitting: 5000,       // 获取定位结果的最长时间，默认：无穷大
                buttonPosition: 'LB',    // 定位按钮的停靠位置
                zoomToAccuracy: true,     // 定位成功后是否自动调整地图视野到用户位置
            });

            map.addControl(geolocation);

            // 定位成功的回调
            document.addEventListener('DOMContentLoaded', function () {
                geolocation.getCurrentPosition((status: any, result: any) => {
                    if (status === 'complete') {
                        // 定位成功，更新地图中心
                        map.setCenter(result.position);

                        // 逆地理编码
                        const geocoder = new AMap.Geocoder();
                        geocoder.getAddress(result.position, (status: any, result: any) => {
                            if (status === 'complete' && result.info === 'OK') {
                                const address = result.regeocodedData.address; // 获取地址信息
                                const addressElement = document.getElementById('address');

                                // 检查元素是否存在
                                if (addressElement) {
                                    addressElement.innerText = address; // 显示地址
                                } else {
                                    console.error('找不到ID为address的元素');
                                }
                            } else {
                                console.error('逆地理编码失败', result);
                            }
                        });
                    } else {
                        console.error(result.message); // 打印失败信息
                    }
                });
            });

        })
        .catch((e) => {
            console.log(e);
        });
    // 详情
    spotDetails();

    fetchRecommendationsByCategoryFn()

});


function spotDetails() {
    // 调用详情的数据接口
    spotDetailsFn(Number(route.query.id)).then(res => {
        console.log(res.data)
        for (let i = 0; i < res.data.length; i++) {

            const items = res.data[i]
            console.log(items)
            // for (let j = 0; j < res.data[i].length; i++) {
            //     console.log(i)
            // }
            console.log(items.images)
            banner.value = items.images
            console.log(banner.value)
        }

        detialisten.value = res.data
    })
}

// 点击游玩攻略
function btnglClick(name: any) {
    console.log(name)
    // 判断点击了哪个，然后调用数据请求
    if (name == 'b') {
        travelGuides()
    } else if (name == 'c') {
        fetchRecommendationsByCategoryFn()
    }
    // 游玩攻略
    // travelGuides()
}

// 游玩攻略
function travelGuides() {
    travelGuidesFn(Number(route.query.id)).then(res => {
        console.log(res.data, 'uuuuuuuuuuuuuuuuuuuuuuuuu')
        playgl.value = res.data
    })
}

// 热门游记
function fetchRecommendationsByCategoryFn() {
    fetchRecommendationsByCategory(String(route.query.id))
        .then(res => {
            console.log(res.data, 'iiiiiiiiiiiiiiiiiiiiiiii999999999999')
            recommendations.value = res.data
        })

}


function mays() {

}


// 点赞总数量
const likesnew = computed(()=>{
    return recommendations.value.reduce((total,item)=>{
        return total + (item.likes || 0)
    },0)
})

// 点赞
function imgClick(id: number) {
    console.log(id,  likesnew,'hhhhhhhhhhhhhhhhhhhhh')
   
    const item = recommendations.value.find(item => item.id === id);
    if (item) {
        item.liked = !item.liked; // 切换liked状态
        
    }
    recommendationsLikesFn(id).then(res=>{
        console.log(res,'hhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhh')
        fetchRecommendationsByCategoryFn()
    })
}

// 用户id
const userId = localStorage.getItem('userId')


// 加入旅行计划接口调用
function travelPlans() {
    console.log(userId, 'id');
    travelPlansFn(
        Number(userId),
        Number(route.query.id),
        Number(route.query.id_id),
        localStorage.getItem('city_name') || '',
        Number(localStorage.getItem('rating') || '')
    ).then(res => {
        console.log('加入旅行计划成功:', res);
    }).catch(err => {
        console.error('加入旅行计划失败:', err);
    });
}
// 点击旅行计划按钮
function lvjhClick(){
    travelPlans()
}


</script>


<style lang="scss" scoped>
// .content {
//     // background-color: #fff;
// }

.banner {
    height: 2.5rem;
    // background-color: red;
    position: relative;

    img {
        width: 100%;
        height: 2.5rem;

    }

    .icons {
        position: absolute;
        // top: 20px;
        z-index: 99999;
    }
}

.main {
    height: 4rem;
    // background-color: #ffff;
    border-top-left-radius: 0.3rem;
    border-top-right-radius: 0.3rem;
    padding: 0.2rem;
    margin-bottom: 30px;
    flex: 1;
    overflow: auto;


    .header_title {
        display: flex;
        width: 75%;
        height: 0.5rem;
        justify-content: space-around;
        align-items: center;
    }
}

.footer {
    position: fixed;
    bottom: 0;
    // background-color: red;
    left: 0;
    width: 100%;
    text-align: center;
    height: 0.5rem;
    // margin-bottom: 20px;

    .van-button {
        width: 80%;
    }
}

// 地图容器
#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 3rem;
}


.contents_main {
    margin-bottom: 30px;

    .title {
        border-bottom: 1px solid #ccc;
        // position: relative;
        bottom: 0.8rem;
    }
}



// 攻略
.gongl {
    display: flex;
    height: 1.5rem;
    // background-color: red;
    margin-top: 0.5rem;

    .left {
        flex: 1;
        height: 100%;
        // background-color: red;

        .van-image {
            width: 90%;
            height: 100%;

        }
    }

    .right {
        flex: 1;
    }
}



// 交通方式图标
.icon_bus {
    width: 70%;
    // background-color: red;
    display: flex;
    justify-content: space-around;

    i {

        &:nth-child(1),
        &:nth-child(2),
        &:nth-child(5) {
            color: blue;
        }
    }
}


.address {
    margin-top: 10px;
    font-size: 14px;
    color: #333;
}




// 热门游记

// .van-img{
//     margin-top: 0.2rme;
// }
.bottom_news{
    display: flex;
    width: 100%;
    // margin-top: 0.3rem;
    .left{
        flex: 1;
        // background-color: red;
        display: flex;
        align-items: center;
        justify-content: start;
    }
    .right{
        flex: 1;
        // background-color: yellow;
        display: flex;
        align-items: center;
        justify-content: end;
    }
}
</style>